package com.wbao.dianniu.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.DialogInterface;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.wbao.dianniu.R;
import com.wbao.dianniu.customView.CanDoBlankGridView;
import com.wbao.dianniu.customView.CustomDialog;
import com.wbao.dianniu.data.QaResponse;
import com.wbao.dianniu.listener.IQuestDelListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.manager.QaDataChangeManager;
import com.wbao.dianniu.manager.QuestDelManager;
import com.wbao.dianniu.manager.QuestGoodManager;
import com.wbao.dianniu.manager.ShareSDKManager;
import com.wbao.dianniu.utils.PictureDownloadUtils;
import com.wbao.dianniu.utils.Utils;

public class MySendQaAdapter extends BaseAdapter implements IQuestDelListener {
	private Context mContext;
	private LayoutInflater mInflater;
	private List<QaResponse> mList;
	private int type;
	private final int TYPE_QA = 1;
	private final int TYPE_PARTIN = 2;
	private QuestDelManager manager;
	private int position;
	
	public MySendQaAdapter(Context context,int type) {
		mContext = context;
		mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		this.type = type;
		manager = new QuestDelManager(mContext);
		manager.addQuestDelListener(this);
		
	}

	/**
	 * 清空数据
	 */
	public void cleanData() {
		if (null != mList) {
			mList.clear();
		}
	}

	public void addDataList(List<QaResponse> list) {
		if (null == mList) {
			mList = new ArrayList<QaResponse>();
		}
		for (int i = 0; i < list.size(); i++) {
			mList.add(list.get(i));
		}
	}
	
	public void removeData(int position){
		mList.remove(position);
		notifyDataSetChanged();
	}
	
	public List<QaResponse> getList(){
		return mList;
	}
	
	@Override
	public int getCount() {
		if (null == mList)
			return 0;
		else
			return mList.size();
	}

	@Override
	public Object getItem(int position) {
		return mList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int index, View convertView, ViewGroup parent) {
		GridHolder holder = null;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.send_qa_list_item, null);
			holder = new GridHolder();
			holder.headIV = (ImageView) convertView.findViewById(R.id.user_head);
			holder.nameTV = (TextView) convertView.findViewById(R.id.user_name);
			holder.labelTV = (TextView) convertView.findViewById(R.id.user_label);
			holder.contentTV = (TextView) convertView.findViewById(R.id.send_qa_content);
			holder.gridview = (CanDoBlankGridView) convertView.findViewById(R.id.send_qa_gridview);
			holder.shareTV = (ImageView) convertView.findViewById(R.id.send_qa_share);
			holder.praiseTV = (TextView) convertView.findViewById(R.id.send_qa_praise_tv);
			holder.praiseIV = (ImageView) convertView.findViewById(R.id.send_qa_praise_iv);
			holder.commentTV = (TextView) convertView.findViewById(R.id.send_qa_comment_tv);
			holder.commentIV = (ImageView) convertView.findViewById(R.id.send_qa_comment_iv);
			holder.imageLayout = (LinearLayout) convertView.findViewById(R.id.send_qa_image_layout);
			holder.deleteBtn = (Button) convertView.findViewById(R.id.send_qa_delete);
			convertView.setTag(holder);
		} else {
			holder = (GridHolder) convertView.getTag();
		}
		if(TYPE_QA == type){
			holder.deleteBtn.setVisibility(View.VISIBLE);
		}else if(TYPE_PARTIN == type){
			holder.deleteBtn.setVisibility(View.GONE);
		}
		final QaResponse resp = mList.get(index);
		PictureDownloadUtils.displayHeadImage(mContext,holder.headIV, resp.headPic);
		holder.nameTV.setText(resp.realName == null ? "" : resp.realName);
		holder.labelTV.setText(resp.label == null ? "" : resp.label);
		if (null != resp.content) {
			holder.contentTV.setText(resp.content);
		}
		if (0 == resp.isGood) {
			holder.praiseIV.setImageResource(R.drawable.click_praise_icon_nor);
		} else {
			holder.praiseIV.setImageResource(R.drawable.click_praise_icon_sel);
		}
		Utils.showPriseCounts(resp.goodCount, holder.praiseTV);
		Utils.showPriseCounts(resp.answerCount, holder.commentTV);
		holder.deleteBtn.setOnClickListener(new DeleteListener(index,resp.id));
		if (TextUtils.isEmpty(resp.questImgs)) {
			holder.gridview.setVisibility(View.GONE); // 没有图片资源就隐藏GridView
			holder.imageLayout.setVisibility(View.GONE);
		} else {
			ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(resp.questImgs);
			holder.imageLayout.setVisibility(View.VISIBLE);
			holder.gridview.setVisibility(View.VISIBLE);
			// 通过图片张数 设置gridview的高度
			double multiple = Math.ceil((float)imageUrls.size()/GlobalContext.NUMCOLUMNS);
	    	int height = (int) (Utils.dip2px(mContext, 80) * multiple + (multiple -1) * Utils.dip2px(mContext, 10));
	    	int width = 0;
	    	if(multiple >= 1){
	    		width = Utils.dip2px(mContext, 80) * GlobalContext.NUMCOLUMNS + (GlobalContext.NUMCOLUMNS -1) * Utils.dip2px(mContext, 5);
	    	}else{
	    		width = Utils.dip2px(mContext, 80) * imageUrls.size() + (imageUrls.size()  -1) * Utils.dip2px(mContext, 5);
	    	}
	    	width = width + Utils.dip2px(mContext, 10);// 加上pendingLeft 10dp
			LinearLayout.LayoutParams lp = new LayoutParams(width, height);
			holder.gridview.setLayoutParams(lp);
			holder.gridview.setAdapter(new NoScrollGridAdapter(mContext,imageUrls));
			// 点击回帖九宫格，查看大图
			holder.gridview.setOnItemClickListener(new MyItemClickListener(imageUrls));
		}
		DetailListener dListener = new DetailListener(resp);
		holder.contentTV.setOnClickListener(dListener);
		holder.headIV.setOnClickListener(dListener);
		holder.nameTV.setOnClickListener(dListener);
		holder.labelTV.setOnClickListener(dListener);
		holder.commentIV.setOnClickListener(dListener);
		holder.praiseIV.setOnClickListener(new praiseListener(index, resp.isGood, resp.goodCount));
		holder.shareTV.setOnClickListener(new ShareListener(resp));
		holder.gridview.setOnTouchInvalidPositionListener(new CanDoBlankGridView.OnTouchInvalidPositionListener() {

            @Override
            public boolean onTouchInvalidPosition(int motionEvent) {
				/*
				 * 当返回false的时候代表交由父级控件处理，当return
				 * true的时候表示你已经处理了该事件并不让该事件再往上传递
				 * 。为了出发listview的item点击就得返回false了
				 */
                return false;
            }
		 });  
		return convertView;
	}
	 /**
	    * 点赞
	 * @author yejianjun
	 *
	 */
	class praiseListener implements OnClickListener{
		   private int isGood;
			private int goodCount;
			private int position;
		   public praiseListener(int position, int isGood,int goodCount) {
			   this.position = position;
			   this.isGood = isGood;
				this.goodCount = goodCount;
		}
		@Override
			public void onClick(View v) {
				if (v.getId() == R.id.send_qa_praise_iv) {
					if (isGood == 0) {
						isGood = 1;
						goodCount++;
					} else {
						isGood = 0;
						goodCount--;
					}
					goodclick(mList.get(position).id);
					QaDataChangeManager.getInstance().priseNotify(mList.get(position).id, isGood, goodCount);
				}
			}

		}
		
		private void goodclick(int questId){
			QuestGoodManager manager = new QuestGoodManager(mContext);
			manager.good(GlobalContext.accountId, questId);
		}
		
	/**
	 * 分享
	 */
	private class ShareListener implements OnClickListener{

		private QaResponse resp;
		
		public ShareListener(QaResponse resp) {
			this.resp = resp;
		}
		
		@Override
		public void onClick(View v) {
			System.out.println("点击了分享");
			String imageUrl = null;
			if(TextUtils.isEmpty(resp.questImgs)){
				imageUrl =  GlobalContext.cdndownUrl +  resp.headPic;
			}else{
				ArrayList<String> imageUrls = PictureDownloadUtils.getInstance().stringToList(resp.questImgs);
				imageUrl = imageUrls.get(0);
			}
			ShareSDKManager.getInstance().showShare(mContext, resp.content, 1, imageUrl, resp.id);
		}
		
	}
	/**
	 *	问题详情、点击头像、点击点赞。点击回复等
	 *
	 */
	private class DetailListener implements OnClickListener{
		private QaResponse resp;
		public DetailListener(QaResponse resp) {
			this.resp = resp;
		}
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.send_qa_content:
			case R.id.send_qa_comment_iv:
				Utils.intoQaDetailActivity(mContext, resp);
				break;
			case R.id.user_head:
			case R.id.user_name:
			case R.id.user_label:
				Utils.intoHeadInfoActivity(resp.accountId, mContext);
				break;
			default:
				break;
			}
		}
	}
	
	private class GridHolder {
		/** 头像 */
		public ImageView headIV;
		/** 昵称 */
		public TextView nameTV;
		/** 标签 */
		private TextView labelTV;
		/** 内容 */
		public TextView contentTV;
		/** 图片显示 */
		public CanDoBlankGridView gridview;
		/** 分享数 */
		public ImageView shareTV;
		/** 点赞数 */
		public TextView praiseTV;
		/** 点赞图标 */
		public ImageView praiseIV;
		/** 回复数 */
		public TextView commentTV;
		/**	回复图标	*/
		public ImageView commentIV;
		/** 图片显示包括 */
		public LinearLayout imageLayout;
		public Button deleteBtn;
	}
	
	class DeleteListener implements OnClickListener{

		private int index;
		private int questId;
		public DeleteListener(int position,int questId) {
			this.index = position;
			this.questId = questId;
		}
		
		@Override
		public void onClick(View v) {
			//
			CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
			builder.setTitle("确认删除该条问答吗？");
			builder.setPositiveButton(mContext.getResources().getString(R.string.confirm),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							position = index;
							manager.deleteQuest(GlobalContext.accountId, questId);
						}
					});
			builder.setNegativeButton(mContext.getResources().getString(R.string.cancel),
					new android.content.DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
			builder.create().show();
		}
		
	} 
	class MyItemClickListener implements OnItemClickListener{

		private ArrayList<String> url;
		public MyItemClickListener(ArrayList<String> url) {
			this.url = url;
		}
		
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			// TODO Auto-generated method stub
			//弹出图片查看按钮
            imageBrower(position, url);
		}
		
	} 
	/**
     * 打开图片查看器
     * 
     * @param position
     * @param urls2
     */
    protected void imageBrower(int position, ArrayList<String> urls2) {
        Utils.imageBrower(mContext, position, urls2);
    }

	@Override
	public void onQuestDelFailure(int errorCode, String errorMsg) {
		
	}

	@Override
	public void onQuestDelSuccess() {
		// 通知其它界面数据改变
		QaDataChangeManager.getInstance().notifyRemove(mList.get(position).id);
//		mList.remove(position);
//		notifyDataSetChanged();
//		QADataChangeManager.getInstance().notifyRemoveByIndex(position);
	}

	public void removeOneData(int questId) {
		// TODO Auto-generated method stub
		for (int i = 0; i < mList.size(); i++) {
			if(mList.get(i).id == questId){
				mList.remove(i);
				notifyDataSetChanged();
				break;
			}
		}
	}

	public void priseNotify(int questId, int isGood, int goodCounts) {
		// TODO Auto-generated method stub
		for (int i = 0; i < mList.size(); i++) {
			if(mList.get(i).id == questId){
				mList.get(i).isGood = isGood;
				mList.get(i).goodCount = goodCounts;
				notifyDataSetChanged();
				break;
			}
		}
	}

	public void replyNotify(int questId, int answerCounts) {
		// TODO Auto-generated method stub
		for (int i = 0; i < mList.size(); i++) {
			if(mList.get(i).id == questId){
				mList.get(i).answerCount = answerCounts;
				notifyDataSetChanged();
				break;
			}
		}
	}

}
